<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入区域名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
     
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="Download" @click="handleExport">导出</el-button>
      </el-col> -->
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
                v-hasPermi="['pms:area:add']"
              
            >新增</el-button>
         </el-col>
          <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleEdit()"
               v-hasPermi="['pms:area:edit']"
            >修改</el-button>
         </el-col> -->
           <!-- <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['pms:area:remove']"
            >删除</el-button>
         </el-col> -->
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="areaList"
      row-key="areaId"
      :tree-props="{ children: 'childs' }"
   
    >
    <!-- @selection-change="handleSelectionChange" -->
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="区域名称" prop="name" :show-overflow-tooltip="true" />
      
      <!-- <el-table-column label="排序" prop="sort" width="80" /> -->
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="区域编码" prop="code" width="180" />
      <el-table-column label="更新时间" prop="updateTime" width="180" />
      <!-- <el-table-column label="操作" align="center" width="250" >
        <template #default="scope">
          <el-button v-hasPermi="['pms:area:add']" link type="primary" v-if="scope.row.status == 1"  icon="Plus" @click="handleAddChild(scope.row)" >新增</el-button>
          <el-button v-hasPermi="['pms:area:edit']" link type="primary"  icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-hasPermi="['pms:area:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button  link type="success" icon="Plus" @click="handleAddBuilding(scope.row)">新增楼宇</el-button>
          <el-button  link type="warning" icon="Plus" v-if="scope.row.buildId || scope.row.pmsUnits" @click="handleAddFloor(scope.row)">新增单元</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 空数据提示 -->
   

    <!-- 新增/编辑区域弹窗 -->
    <el-dialog @close="handleClose" :title="dialogTitle" v-model="dialogVisible" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="上级区域" prop="parentId">
          <el-tree-select
          default-expand-all
            v-model="form.parentId"
            :data="areaOptions"
            :props="{ value: 'areaId', label: 'name', children: 'childs' }"
            value-key="areaId"
            placeholder="请选择上级区域"
            check-strictly
            style="width: 100%"
          />
        </el-form-item> -->
        <!-- <el-form-item  v-if="!form.parentId" label="所属小区" prop="communityId">
          <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%">
            <el-option
              v-for="item in communityOptions"
              :key="item.communityId"
              :label="item.name"
              :value="item.communityId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="区域名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item> -->
        
        <!-- <el-form-item v-if="!form.areaId" label="区域编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入区域编码" />
        </el-form-item> -->
        <!-- <div v-if="!form.areaId" style="color: red;font-size: 14px;margin-bottom: 10px;margin-left: 100px;">区域编号不可更改</div> -->
        <!-- <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" style="width: 100%" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增楼宇弹窗 -->
    <el-dialog
      :title="'新增楼宇'"
      v-model="buildingDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form ref="buildingFormRef" :model="buildingForm" :rules="buildingRules" label-width="80px">
        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="buildingForm.name" placeholder="请输入楼宇名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="buildingDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSaveBuilding">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增单元弹窗 -->
    <el-dialog
      :title="'新增单元'"
      v-model="floorDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form ref="floorFormRef" :model="floorForm" :rules="floorRules" label-width="80px">
        <el-form-item label="单元名" prop="name">
          <el-input v-model="floorForm.name" placeholder="请输入单元名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="floorDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSaveFloor">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs,onMounted } from 'vue'
import { listArea, addArea, updateArea, delArea,addBuild,addFloor } from '@/api/house/area'
import { listCommunity } from '@/api/house/community'
// import { addBuilding } from '@/api/house/building'
import { number } from 'echarts'

const { proxy } = getCurrentInstance()
const statusOptions = [
  { value: '1', label: '正常' },
  { value: '2', label: '停用' }
]

const loading = ref(false)
const areaList = ref([])
const total = ref(0)
const multiple = ref(true)
const ids = ref([])

const data = reactive({
  queryParams: {
    //  communityId:0,
    // parentId: 0,
    pageNum: 1,
    pageSize: 10,
    name: '',
    status: '',
    sort: ''
  }
})
const { queryParams } = toRefs(data)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const communityOptions = ref([])
const areaOptions = ref([])
const single = ref([])
const form = reactive({
  parentId: '',
  name: '',
  status: '1',
  sort: '',
  communityId: '',
  level: 1 // 默认最外层
})
const rules = {
  name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
  sort: [
    { required: true, message: '请输入排序', trigger: 'change' },
    { type: 'number', message: '排序必须为数字', trigger: 'change' },
    { validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请输入排序'))
        } else {
          callback()
        }
      }, trigger: 'change'
    }
  ],
  communityId: [{ required: true, message: '请选择小区', trigger: 'change' }]
}

// 楼宇弹窗相关
const buildingDialogVisible = ref(false)
const buildingFormRef = ref(null)
const buildingForm = reactive({
  name: '',
  areaId: null,
  communityId: null
})
const buildingRules = {
  name: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }]
}

// 单元弹窗相关
const floorDialogVisible = ref(false)
const floorFormRef = ref(null)
const floorForm = reactive({
  name: '',
  buildId: null,
  communityId: null
})
const floorRules = {
  name: [{ required: true, message: '请输入单元名', trigger: 'blur' }]
}

function handleClose() {
  dialogVisible.value = false
  formRef.value.resetFields()
}

function listToTree(list, parentId = "0") {
  return list
    .filter(item => item.parentId === parentId)
    .map(item => {
      const children = listToTree(list, item.areaId)
      return children.length ? { ...item, children } : { ...item }
    })
}

function getList() {
  loading.value = true
  listArea({
    pageNum: 1,
    pageSize: 1000,
    status:1
  })
  .then(res => {
    areaOptions.value =  [
      {
        areaId:0,
        name:"最上级",
        childs: res?.rows || []
      }
    ]
  })
  listArea(queryParams.value).then(res => {
    console.log(res)
    let flatList = res?.rows || []
    console.log("flatList",flatList)
    flatList=flatList.map(item=>{
       item.childs=[]
      if(item.pmsBuilds){
        item.childs=item.pmsBuilds
      }
      return item
    })
    // let value = listToTree(flatList, "0") // 0为根节点parentId
    // console.log("value",value)
    areaList.value = flatList
     // 用于el-tree-select多层级选择
    total.value = flatList.length
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  queryParams.value.name = ''
  queryParams.value.status = ''
  queryParams.value.sort = ''
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.areaId)
  multiple.value = !selection.length
  single.value = selection.length != 1

}

function handleAdd() {
  dialogTitle.value = '新增'
  form.parentId = ''
  form.name = ''
  form.status = 1
  form.sort = ''
  form.communityId = ''
  form.areaId = ''
  form.level = 1 // 新增最外层
  dialogVisible.value = true
  formRef.value.resetFields()
}
function handleEdit(row) {
  if(!row){
    let id=ids.value[0]
    row=areaList.value.find(item => item.areaId == id)
  }
 
  if(row.status == 2){
    proxy.$modal.msgError("该区域已停用，无法编辑")
    return
  }
  console.log("row",row)
  dialogTitle.value = '编辑'
  form.areaId = row.areaId
  form.parentId = row.parentId 
  form.name = row.name 
  form.status = Number(row.status) 
  form.sort =  Number(row.sort) 
  form.communityId =Number(row.communityId) 
  form.code = row.code 
  
  console.log("form",form)
  dialogVisible.value = true
}
function handleDelete(row) {
  const delIds = row ? [row.areaId] : ids.value
  if (!delIds.length) return

 proxy.$modal.confirm('是否确认删除区域编号为"' + delIds + '"的数据项?').then(function () {
    return delArea(delIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})

  // // 二次确认
  // window.$confirm?.('确定要删除所选区域吗？', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).then(() => {
  //   return Promise.all(delIds.map(id => delArea(id)))
  // }).then(() => {
  //   window.$message?.success?.('删除成功') || this?.$message?.success('删除成功')
  //   getList()
  // }).catch(() => {})
}
function handleImport() {
  // 预留导入逻辑
}
function handleExport() {
  // 预留导出逻辑
}
function handleSave() {
  formRef.value.validate(valid => {
    if (valid) {
      let level = 1
      if (form.parentId && form.parentId !== '0' && form.parentId !== 0) {
        level = getParentLevel(form.parentId)
      }
      // 自动生成 code
      const parentNames = getParentNames(form.parentId)
      const code = parentNames.length > 0 ? parentNames.concat([form.name]).join('#') : form.name
      const payload = {
        areaId: form.areaId,
        parentId: form.parentId,
        name: form.name,
        status: Number(form.status),
        sort: Number(form.sort),
        communityId: Number(form.communityId),
        code: code,
        level: level
      }
      if(form.areaId){
        // 编辑时不允许改 code
        delete payload.code
      }
      const req = dialogTitle.value === '编辑' ? updateArea(payload) : addArea(payload)
      req.then(() => {
        window.$message?.success?.('保存成功') || this?.$message?.success('保存成功')
        dialogVisible.value = false
        handleClose()
        getList()
      })
    }
  })
}

function handleAddChild(parent) {
  dialogTitle.value = '新增'
  form.parentId = parent.areaId
  form.name = ''
  form.status = 1
  form.sort = ''
  form.communityId = parent.communityId
  form.code = undefined
  form.areaId = undefined
  form.level = (parent.level ? Number(parent.level) + 1 : getParentLevel(parent.areaId))
  dialogVisible.value = true
}

// 递归查找父级 level
function getParentLevel(parentId) {
  if (!parentId || parentId === '0' || parentId === 0) {
    return 1
  }
  const parent = areaList.value.find(item => item.areaId == parentId)
  if (parent && parent.level) {
    return Number(parent.level) + 1
  } else if (parent) {
    return getParentLevel(parent.parentId) + 1
  } else {
    return 2
  }
}

// 递归查找所有上级 name
function getParentNames(parentId) {
  if (!parentId || parentId === '0' || parentId === 0) {
    return []
  }
  const parent = areaList.value.find(item => item.areaId == parentId)
  if (parent) {
    return [...getParentNames(parent.parentId), parent.name]
  } else {
    return []
  }
}

// 点击"新增楼宇"
function handleAddBuilding(area) {
  buildingForm.name = ''
  buildingForm.areaId = area.areaId
  buildingForm.communityId = area.communityId
  buildingDialogVisible.value = true
}

// 保存楼宇
function handleSaveBuilding() {
  buildingFormRef.value.validate(valid => {
    if (valid) {
      // code 规则：上级区域名#楼宇名
      const area = areaList.value.find(item => item.areaId == buildingForm.areaId)
      const code = area ? `${area.name}#${buildingForm.name}` : buildingForm.name
      const payload = {
        name: buildingForm.name,
        code,
        areaId: buildingForm.areaId,
        communityId: buildingForm.communityId
      }
      addBuild(payload).then(() => {
       proxy.$message?.success('保存成功')
        buildingDialogVisible.value = false
        // 可选：刷新楼宇列表或区域列表
      })
    }
  })
}

// 点击"新增单元"
function handleAddFloor(build) {
  floorForm.name = ''
  floorForm.buildId = build.buildId || build.areaId
  floorForm.communityId = build.communityId
  floorDialogVisible.value = true
}

// 保存单元
function handleSaveFloor() {
  floorFormRef.value.validate(valid => {
    if (valid) {
      // code 规则：楼宇名#单元名
      const buildName = buildNameById(floorForm.buildId)
      const code = buildName ? `${buildName}#${floorForm.name}` : floorForm.name
      const payload = {
        name: floorForm.name,
        code,
        buildId: floorForm.buildId,
        communityId: floorForm.communityId
      }
      addFloor(payload).then(() => {
        proxy.$message?.success('保存成功')
        floorDialogVisible.value = false
        // 可选：刷新单元/楼宇/区域列表
      })
    }
  })
}

// 辅助函数：根据 buildId 查找楼宇名
function buildNameById(buildId) {
  // 先在 areaList 的所有楼宇中查找
  for (const area of areaList.value) {
    if (area.pmsBuilds && Array.isArray(area.pmsBuilds)) {
      const build = area.pmsBuilds.find(b => b.buildId == buildId)
      if (build) return build.name
    }
  }
  return ''
}

onMounted(() => {
  listCommunity().then(res => {
    communityOptions.value = res.rows || []
  })
})

getList()
</script> 